package com.xmindguoguo.boot.config.error;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.xmindguoguo.boot.common.constant.GlobalConstant;
import com.xmindguoguo.boot.common.constant.SessionConstant;
import com.xmindguoguo.boot.core.log.LogManager;
import com.xmindguoguo.boot.core.log.factory.LogModelFactory;
import com.xmindguoguo.boot.core.log.factory.LogTaskFactory;
import com.xmindguoguo.boot.core.shiro.ShiroKit;
import com.xmindguoguo.boot.modular.system.model.TSystemErrorLogModel;
import com.xmindguoguo.boot.util.http.HttpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理 ，可以进行参考
 * 
 */
@Slf4j
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mv;
        // 开发环境打印异常，正式环境请注销
        String errorMsg = "未知错误,请联系管理员";
        String viewStr = "/common/error/error_msg";
        if (StringUtils.isNotBlank(ShiroKit.getSessionAttr(SessionConstant.SYSTEM_ERROR_INFO))) {
            errorMsg = ShiroKit.getSessionAttr(SessionConstant.SYSTEM_ERROR_INFO);
            ShiroKit.setSessionAttr(SessionConstant.SYSTEM_ERROR_INFO, ""); // 重新变成空
        }
        // shiro异常拦截
        if (HttpUtil.isAjax(request)) {
            mv = new ModelAndView();
            FastJsonJsonView view = new FastJsonJsonView();
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("code", "500");
            attributes.put("msg", errorMsg);
            view.setAttributesMap(attributes);
            mv.setView(view);
        } else {
            mv = new ModelAndView(viewStr);
            request.setAttribute(GlobalConstant.Const.ERROR_MSG, errorMsg);
        }
        log.error(ExceptionUtils.getFullStackTrace(ex));
        // 记录错误日志
        TSystemErrorLogModel errorLogModel = LogModelFactory.getTSystemErrorLogModel(request, handler, ex);
        LogManager.me().executeLog(LogTaskFactory.errorLog(errorLogModel));
        return mv;
    }

}
